<?php
// +----------------------------------------------------------------------
// | astp [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author 荒年 < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 处理接收回复消息
// +----------------------------------------------------------------------
namespace app\wewhat\controller;

use think\Controller;
use app\wewhat\model\Fxuser as fxuserModel;
use app\wewhat\service\HttpRequest;

class Accept extends Controller
{
  //处理接收文本
  public function acceptMsg()
  {
    $xml = file_get_contents('php://input');
    $obj = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
    $MsgType = $obj->MsgType;
    $fun = $MsgType.'Fun';
    echo $ret = $this->$fun($obj);
  }

  //处理回复文本
  private function textFun($obj)
  {
    $content = $obj->Content;
    if('音乐' == $content){
      return $this->musicFun($obj);
    } else if(strstr($content,'位置-')){
      // 餐饮
      # 得到关键词
      $http = new HttpRequest();
      $kw = str_replace('位置-','',$content);
      $kw = trim($kw);
      $model = new fxuserModel();
      $openId = $obj->FromUserName;
      $wz = $model->where('openid','=',$openId)->find();
      $url = 'restapi.amap.com/v3/place/around?key=e84643472fd7ed90447265644c3198fc&location=118.905731,42.272568&keywords='.$kw.'&types=050100&radius=10000&offset=1&page=1&extensions=all';
      $json = $http->http_request($url);
      $arr = json_decode($json,true);
      # 判断搜索结果
      if (count($arr['pois']) == 0) {
        $content = '没有找到相关服务';
      } else {
        $content = "🚩🚩🚩🚩🚩🚩🚩🚩🚩🚩🚩\n";
        $content .= "名称：".$arr['pois'][0]['name']."\n";
        $content .= "地址：".$arr['pois'][0]['address']."\n";
        $content .= "距离：".$arr['pois'][0]['distance']."米\n";
        $content .= "🚩🚩🚩🚩🚩🚩🚩🚩🚩🚩🚩";
      }
      return $this->createText($obj,$content);
    }
    return $this->createText($obj,$content);
  }

  //生成文本消息XML
  private function createText($obj,$content)
  {
    $xml = '<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[%s]]></Content>
      </xml>';
    $str = sprintf($xml,$obj->FromUserName,$obj->ToUserName,time(),$content);
    return $str;
  }

  //处理回复图片
  private function imageFun($obj)
  {
    $mediaid = $obj->MediaId;
    return $this->createImage($obj,$mediaid);
  }

  //生成图片消息XML
  private function createImage($obj,$mediaid)
  {
    $xml = '<xml>
      <ToUserName><![CDATA[%s]]></ToUserName>
      <FromUserName><![CDATA[%s]]></FromUserName>
      <CreateTime>%s</CreateTime>
      <MsgType><![CDATA[image]]></MsgType>
      <Image>
        <MediaId><![CDATA[%s]]></MediaId>
      </Image>
    </xml>';
    $str = sprintf($xml,$obj->FromUserName,$obj->ToUserName,time(),$mediaid);
    return $str;
  }

  //处理回音乐
  private function musicFun($obj)
  {
    //图片媒体id
    $mediaid = 'sKdh-QlyRQjRhCiVlm16dFx7_p6b3NJy09eYffEEXZgp6JkTt-EKe930ck-R7sDB';
    //音乐播放地址
    $musicUrl = 'http://www.kugou.com/song-36/d7085d4.html?from_360#hash=0649B18ACB158438F7B4EFA80F23159D&album_id=0';
    return $this->createMusic($obj,$mediaid,$musicUrl);
  }

  //生成音乐消息XML
  private function createMusic($obj,$mediaid,$musicUrl)
  {
    $xml = '<xml>
      <ToUserName><![CDATA[%s]]></ToUserName>
      <FromUserName><![CDATA[%s]]></FromUserName>
      <CreateTime>%s</CreateTime>
      <MsgType><![CDATA[music]]></MsgType>
      <Music>
        <Title><![CDATA[夜空中最亮的星]]></Title>
        <Description><![CDATA[一首非常好听的歌]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
      </Music>
    </xml>';
    $str = sprintf($xml,$obj->FromUserName,$obj->ToUserName,time(),$musicUrl,$musicUrl,$mediaid);
    return $str;
  }

  // 语音处理
  private function voiceFun($obj)
  {
    $content = (string)$obj->Recognition;
    $content = !empty($content) ? $content : '语音无法识别'; 
    return $this->createText($obj,$content);
  }

  //处理点击事件
  private function eventFun($obj)
  {
    $model = new fxuserModel();
    $event = $obj->Event;
    switch( $event ){
      # 点击事件
      case 'CLICK':
        return $this->clickFun($obj);
        break;
      # 关注事件
      case 'subscribe' :
        $eventKey = $obj->EventKey;
        $eventKey = (string)$eventKey;
        $openId = $obj->FromUserName;
        
        // 三级分销添加数据库

        if(empty($eventKey)){ //顶级添加数据库
          $model->save(['openid' => $openId]);
        } else {
          # 得到上级id
          $id = str_replace('qrscene_','',$eventKey);
          $id = (int)$id;
          # 查询记录
          $row = $model->where('id','=',$id)->find();
          # 添加本人的记录数据
          $model->save([
            'openid' => $openId,
            'f1' => $row['openid'],
            'f2' => $row['f1'],
            'f3' => $row['f2']
          ]);
        }
        
        return $this->createText($obj,"欢迎关注我们的公众平台\n这里有你想要的一切！");
        break;
      # 位置信息
      case 'LOCATION' : 
        $openId = $obj->FromUserName;
        $longitude = $obj->Longitude;
        $latitude = $obj->Latitude;
        $model->save(['longitude'=>$longitude,'latitude'=>$latitude],['openid'=>$openId]);
        break;
    }
  }

  //处理点击事件
  private function clickFun($obj)
  {
    $eventKey = $obj->EventKey;
    if( $eventKey == 'key001' ){
      return $this->createText($obj,'点击001');
    } else if('key002' == $eventKey){
      return $this->createText($obj,'点击002');
    } else {
      return $this->createText($obj,'点击003');
    }
  }

}

?>